//
//  DataBaseManager.m
//  MyProject
//
//  Created by 石美妮 on 16/1/27.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "DataBaseManager.h"
#import <FMDatabase.h>
#import <FMDatabaseQueue.h>
#import "Masseage.h"

@interface DataBaseManager ()

@property(nonatomic, strong) FMDatabase *fmdb;// 数据库对象

@end

@implementation DataBaseManager

+(DataBaseManager *)shareInstance
{
    // 写成单例
    static DataBaseManager *dbManager = nil;
    if (!dbManager) {
        dbManager = [[DataBaseManager alloc] init];
    }
    return dbManager;
}
#pragma mark - 打开数据库
- (void)openDB
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fmdb.db"];
    NSLog(@"path:%@", path);
    // 创建数据库
    self.fmdb = [[FMDatabase alloc] initWithPath:path];
    // 打开数据库
    BOOL result = [_fmdb open];
    if (result) {
        NSLog(@"数据库打开成功");
    }else {
        NSLog(@"数据库打开失败");
    }
}
#pragma mark - 创建表
- (void)creatTabel
{
    NSString *creatSQL = @"CREATE TABLE  IF NOT EXISTS massage(number integer PRIMARY KEY AUTOINCREMENT, mail text, name text, pwd text, chepwd text)";
    [self executeSQL:creatSQL message:@"创建表"];
}
#pragma mark - 删除表
- (void)dropTabel
{
    NSString *dropSQL = @"DROP TABLE massage";
    [self executeSQL:dropSQL message:@"删除表"];
}
#pragma mark - 插入
- (void)insertMassage:(Masseage *)mass
{
    NSString *inserSQL = [NSString stringWithFormat:@"INSERT INTO massage(mail, name, pwd, chepwd) VALUES('%@','%@', '%@', '%@')",mass.mail, mass.name, mass.pwd, mass.chepwd];
    [self executeSQL:inserSQL message:@"插入数据"];
}
#pragma mark - 查询
- (NSMutableArray *)select
{
    NSMutableArray *arr = [NSMutableArray array];
     NSString *selectSQL = @"SELECT * FROM massage";
    FMResultSet *resultSet = [_fmdb executeQuery:selectSQL];
    // 遍历每一行信息
    while ([resultSet next]) {
        // 获取每一行信息
        NSString *mail = [resultSet stringForColumn:@"mail"];
        NSString *name = [resultSet stringForColumn:@"name"];
        NSString *pwd = [resultSet stringForColumn:@"pwd"];
        NSString *chepwd = [resultSet stringForColumn:@"chepwd"];
        Masseage *m = [[Masseage alloc] init];
        m.mail = mail;
        m.name = name;
        m.pwd = pwd;
        m.chepwd = chepwd;
        // 添加到数组中
        [arr addObject:m];
    }
    return arr;
}


- (void)executeSQL:(NSString *)sql message:(NSString *)mes
{
    // 执行
    BOOL result = [_fmdb executeUpdate:sql];
    // 判断
    if (result) {
        NSLog(@"%@成功", mes);
    }else {
        NSLog(@"%@失败", mes);
    }
}


@end
